﻿using System;
using System.Web.Mvc;
using Yala.Core.Authentication;
using Yala.Models.AuthProviders;
using Yala.Models.Users;

namespace Yala.Client.Web.MVC.Controllers {
    public class OpenIdAccountController : Controller {
        private readonly IAuthProvidersRepository _authProvidersRepo;
        private readonly IUsersRepository _usersRepo;
        private readonly IFormsAuthentication _formsAuthentication;
        private readonly IMembership _membership;

        public OpenIdAccountController(IUsersRepository usersRepo,
                                       IAuthProvidersRepository authsProviderRepo,
                                       IFormsAuthentication formsAuthentication,
                                       IMembership membership) {
            _usersRepo = usersRepo;
            _authProvidersRepo = authsProviderRepo;
            _formsAuthentication = formsAuthentication;
            _membership = membership;
        }

        // URL: /OpenIdAccount/LogOff
        public ActionResult LogOff() {
            _formsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOn() {
            var provider = _authProvidersRepo.Single(x => x.Name.Contains("google"));
 
           //Validate user
            dynamic result = _membership.ValidateUser(provider.ServiceUrl);
            if (result.Authenticated) {
                
                string claimid = result.ClaimId;
                var user = _usersRepo.Single(x => x.OpenId == claimid);
               
                if (user == null) {
                    if (string.IsNullOrEmpty(result.Email) == false) {
                        user = new User {
                            AuthProvider = provider,
                            Username = "New User",
                            OpenId = result.ClaimId,
                            Email = result.Email,
                            LastLogOnDate = DateTime.Now,
                        };
                        _usersRepo.Add(user);
                    }
                } else {
                    user.LastLogOnDate = DateTime.Now;
                    _usersRepo.Update(user);
                }

                //Commit changes and sign in
                _usersRepo.CommitChanges();
                _formsAuthentication.SignIn(user.Id, user.Username, false);

                return RedirectToAction("Profile", "Account");
            } else {
                return RedirectToAction("Index", "Home");
            }
            return new EmptyResult();
        }



    }
}
